<template>
  <div>
    <!-- 上半部分 -->
    <el-card style="margin:20px 0">
      <!-- 三联下拉框 -->
      <!-- 设置自定义事件，以实现子组件向父组件传送数据 -->
      <CategorySelect @getCategoryId="getCategoryId" :show="!isShowTable"></CategorySelect>
    </el-card>

    <!-- 下半部分 -->
    <el-card>
      <!-- 1  初始表单部分 -->
      <div v-show="isShowTable">
        <!-- 添加按钮 -->
        <el-button type="primary" icon="el-icon-plus" :disabled="!c3Id" @click="addAttr">添加属性</el-button>
        <!-- 表格 -->
        <el-table :data="attrList" style="width: 100%; margin: 20px 0;" border>
          <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="150"></el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{row,$index}">
              <el-tag
                type="success"
                v-for="attrValue in row.attrValueList"
                :key="attrValue.id"
                style="margin: 0 5px"
              >{{attrValue.valueName}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150">
            <template slot-scope="{row,$index}">
              <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateAttr(row)" style="margin: 0 10px;"></el-button>
              <!-- popconfirm 气泡窗应用 -->
              <el-popconfirm :title="`确定删除${row.attrName}?`" @onConfirm="deleteAttr(row)">
                <el-button type="danger" icon="el-icon-delete" size="mini" slot="reference"></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 2  添加/修改属性表单 -->
      <div v-show="!isShowTable">
        <el-form :inline="true" ref="form" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input placeholder="请输入属性名" v-model="attrInfo.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" @click="addAttrValue" :disabled="!attrInfo.attrName">添加属性值</el-button>
        <el-button @click="isShowTable= true">取消</el-button>
        <el-table style="width: 100%;margin: 20px 0;" border :data="attrInfo.attrValueList">
          <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
          <el-table-column prop="prop" label="属性值名称" width="width">
            <template slot-scope="{row,$index}">
              <!-- 二选一 -->
              <el-input
                ref="input"
                v-model="row.valueName"
                placeholder="请输入属性值"
                size="mini"
                v-if="row.flag"
                @blur="displaySpan(row)"
                @keyup.native.enter="displaySpan(row)"
              ></el-input>
              <span v-else @click="displayInput(row)" style="display:block">{{row.valueName}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{row,$index}">
              <!-- popconfirm 气泡窗应用 -->
              <el-popconfirm :title="`确定删除${row.valueName}?`" @onConfirm="deleteAttrValue($index)">
                <el-button type="danger" icon="el-icon-delete" size="mini" slot="reference"></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="addOrUpdateAttr" :disabled="attrInfo.attrValueList.length<1">保存</el-button>
        <el-button @click="isShowTable= true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
//

export default {
  name: 'Attr',
  data() {
    return {
      c1Id: '',
      c2Id: '',
      c3Id: '',
      // 接收平台属性数据
      attrList: [],
      isShowTable: true,
      // 增加/修改属性名用的数据
      attrInfo: {
        attrName: '', // 属性名
        attrValueList: [],
        categoryId: 0,
        categoryLevel: 3
      }
    }
  },
  methods: {
    // 获取子组件传送来的各级分类 id
    getCategoryId({ cId, level }) {
      if (level === 1) {
        this.c1Id = cId
        this.c2Id = ''
        this.c3Id = ''
      } else if (level === 2) {
        this.c2Id = cId
        this.c3Id = ''
      } else if (level === 3) {
        this.c3Id = cId
        // 当获取到3级id后，生成下方表单数据
        this.getAttrList()
      }
    },
    // 向服务器发请求，根据获得各级id，生成表单数据
    async getAttrList() {
      const { c1Id, c2Id, c3Id } = this
      const result = await this.$API.attr.reqAttrList(c1Id, c2Id, c3Id)
      if (result.code === 200) {
        this.attrList = result.data
      }
    },
    // 点击初始页面上的添加按钮时
    addAttr() {
      this.isShowTable = false
      this.attrInfo = {
        attrName: '', // 属性名
        attrValueList: [],
        categoryId: this.c3Id, // 且在点击添加时，能够获得当前的三级id
        categoryLevel: 3
      }
    },
    // 点击修改属性时
    updateAttr(row) {
      this.isShowTable = false
      // 由于数据结构嵌套了几层，较为复杂，因此使用 JSON将其转为字符串，再转为对象，避免地址相同
      this.attrInfo = JSON.parse(JSON.stringify(row))
      // 且在修改属性值时，为对应的属性值元素添加上 flag，以实现切换
      this.attrInfo.attrValueList.forEach(item => {
        // 记得要添加响应式数据
        this.$set(item, 'flag', false)
      })
    },
    // 添加属性值
    addAttrValue() {
      // 向属性值数值内添加元素
      this.attrInfo.attrValueList.push({
        // 属性值的名称要与API接口要求的一致
        attrId: this.attrInfo.id, // 若是修改已有属性，则需要为其赋上已有属性的id，否则就是undefined
        valueName: '',
        flag: true // 用于控制显示input还是span
      })
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    },
    // 显示span
    displaySpan(row) {
      // 判断是否为空
      if (!row.valueName.trim()) {
        this.$message('属性值不能为空')
        return
      }
      // 判断是否重复
      let isRepeat = this.attrInfo.attrValueList.some(item => {
        // 除去row本身，看其他成员中是否有与row相同的
        if (row !== item) return row.valueName == item.valueName
      })
      if (isRepeat) {
        this.$message('属性值重复')
        return
      }
      row.flag = false
    },
    // 显示input
    displayInput(row) {
      row.flag = true
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    },
    // 气泡确认框确认删除整个属性
    async deleteAttr(row) {
      const result = await this.$API.attr.reqDeleteAttr(row.id)
      if (result.code === 200) {
        this.getAttrList()
      }
    },
    // 气泡确认框确认删除单个属性值
    deleteAttrValue(index) {
      this.attrInfo.attrValueList.splice(index, 1)
    },
    // 保存修改、新增的属性，并上传服务器
    async addOrUpdateAttr() {
      // 过滤掉属性值为空的
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(item => {
        if (item.valueName !== '') {
          // 删除 flag属性
          delete item.flag
          return true
        }
      })
      // 向服务器发送请求
      try {
        await this.$API.attr.reqAddOrUpdataAttr(this.attrInfo)
        this.isShowTable = true
        this.$message({ type: 'success', message: '保存成功' })
        this.getAttrList()
      } catch (error) {
        this.$message({ type: 'error', message: '保存失败' })
      }
    }
  }
}
</script>

<style>
</style>